package ltd.jdsoft.cute.prometheus.spi.impl;

import org.aspectj.lang.ProceedingJoinPoint;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.prometheus.client.Histogram;
import io.prometheus.client.Histogram.Timer;
import ltd.jdsoft.cute.prometheus.MonitorChain;
import ltd.jdsoft.cute.prometheus.spi.Monitor;

public class LatencyHistogram implements Monitor {

  private static Logger logger = LoggerFactory.getLogger(LatencyHistogram.class);
  private static Histogram latencyHistogram = Histogram.build().name("latency")
      .buckets(DEFAULT_BUCKETS).help("接口耗时直方图").labelNames(LABEL_NAMES).register();

  @Override
  public Object process(ProceedingJoinPoint joinPoint, MonitorChain chain, String... labelValues)
      throws Throwable {
    logger.debug("start monitor latency...");
    Timer timer = null;
    try {
      timer = latencyHistogram.labels(labelValues).startTimer();
      return joinPoint.proceed();
    } finally {
      timer.observeDuration();
      logger.debug("end monitor latency...");
    }
  }
}
